import json
import logging
import random
from datetime import datetime

import chinese_calendar
import requests

from ImgHandle import get_oss_image_url, get_cos_image_url


# 获取当今日期
def get_current_date():
    today = datetime.now()
    today_date = today.strftime("%Y-%m-%d")
    weekdays = ["Mon.", "Tue.", "Wed.", "Thu.", "Fri.", "Sat.", "Sun."]
    today_weekday = weekdays[today.weekday()]
    return f"{today_date} {today_weekday}"


# 每日星座运势
def get_daily_star():
    file_path = 'resource/stars.json'
    stars = ["白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
             "天蝎座", "射手座", "摩羯座", "水瓶座", "双鱼座"]
    daily_star_url = f'https://api.leafone.cn/api/horoscope?name={random.choice(stars)}'
    response = requests.get(daily_star_url)
    if response.status_code == 200:
        current_data = response.json()
        with open(file_path, 'w', encoding='utf-8') as file:
            current_data['data']['imageUrl'] = get_cos_image_url()
            json.dump(current_data['data'], file, ensure_ascii=False, indent=4)
            return current_data['data']
    elif response.status_code == 203:
        logging.error("请求超过QPS限制：10 秒 1 次")
        return "请求超过QPS限制：10 秒 1 次", 502
    else:
        logging.error("Failed to fetch daily text")
        return "Failed to fetch daily text", 500


# 获取节假日
def get_holidays():
    start_year = datetime.now().date()
    end_year = datetime(2025, 12, 31).date()
    c_holidays = chinese_calendar.get_holidays(start_year, end_year)
    vacation = {
        None: "周末",
        "New Year's Day": "元旦",
        "Spring Festival": "春节",
        "Tomb-sweeping Day": "清明节",
        "Labour Day": "劳动节",
        "Dragon Boat Festival": "端午节",
        "National Day": "国庆节",
        "Mid-autumn Festival": "中秋节"
    }

    vacations2026 = {
        datetime(2026, 1, 1).date(): "元旦",
        datetime(2026, 2, 17).date(): "春节",
        datetime(2026, 4, 5).date(): "清明节",
        datetime(2026, 5, 1).date(): "劳动节",
        datetime(2026, 6, 19).date(): "端午节",
        datetime(2026, 9, 25).date(): "中秋节",
        datetime(2026, 10, 1).date(): "国庆节"
    }

    result = {}
    for holiday in c_holidays:
        _, name = chinese_calendar.get_holiday_detail(holiday)
        chinese_name = vacation.get(name, name)

        days_diff = (holiday - start_year).days
        if chinese_name not in result:
            result[chinese_name] = days_diff

    for date, name in vacations2026.items():
        days_diff = (date - start_year).days
        if name not in result:
            result[name] = days_diff

    return result